#include "gameroom.h"
#include<QPainter>
#include<QIcon>
#include<QTimer>
#include<QPushButton>
#include<QMessageBox>
#include <QPen>
#include<QFile>
#include<QTextStream>
gameroom::gameroom(QWidget *parent) : QWidget(parent)
{
this->setWindowIcon(QIcon(":/icon.png"));
    this->setWindowTitle("游戏进行中");




    { //贪吃蛇的初始化
    snakeList.push_back(QRectF(this->width()*0.5,this->height()*0.5,snakeWidth,snakeHeight));
     moveUp();
      moveUp();
   //产生食物
   creatFood();}


   //处理蛇的移动
 {
        timer=new  QTimer(this);//定时器
  //蛇开始移动之后的一些处理
  connect(timer,&QTimer::timeout,[=](){
      //判断食物与蛇是否相交
      int foodNumber=1;
      if(snakeList.front().intersects(foodNode))
      {
          creatFood();
          foodNumber++;
      }
      //确定移动方向
      while( foodNumber--)
     {
          switch (snakeDireaction)
      {
          case moveMent::UP:
             moveUp();
          break;
      case moveMent::DOWN:
          moveDown();
            break;
      case moveMent::LEFT:
          moveLeft();
            break;
      case moveMent::RIGHT:
          moveRight();
            break;
      }
      }
      //删除最后一个结点
      snakeList.pop_back();
      //更新链表
      update();
  });
    }



  //定义开始与暂停按钮
 {
      QPushButton * startButton=new QPushButton(this);
   QPushButton * stopButton=new QPushButton(this);
    startButton->move(850,210);
    stopButton->move(850,260);
     startButton->setText("开始");
     stopButton->setText("暂停");
     QFont font("黑体",20);
      startButton->setFont(font);
      stopButton->setFont(font);

      //点击开始按钮的反应
      connect(startButton,&QPushButton::clicked,[=](){
          //游戏开始
          isGameStart=true;
          //打开定时器
         timer->start(snakeSpeed) ;
                 //加声音
            sound=new QSound(":/game.wav");
         sound->play();
         //会一直响
         sound->setLoops(-1);
      });
       //点击暂停按钮的反应
      connect(stopButton,&QPushButton::clicked,[=](){
          //游戏开始
          isGameStart=false;
          //打开定时器
        timer->stop();
        sound->stop();
      });
                  }




      //方向控制
    {  QPushButton* upButton=new QPushButton(this);
       QPushButton* downButton=new QPushButton(this);
        QPushButton* leftButton=new QPushButton(this);
         QPushButton* rightButton=new QPushButton(this);


      upButton->move(870,550);
        downButton->move(870,610);
         leftButton->move(830,580);
         rightButton->move(910,580);

         upButton->setStyleSheet("QPushButton{border:0xp}");
           downButton->setStyleSheet("QPushButton{border:0xp}");
             leftButton->setStyleSheet("QPushButton{border:0xp}");
               rightButton->setStyleSheet("QPushButton{border:0xp}");


               QFont font("黑体",36);
                upButton->setFont(font);
                 downButton->setFont(font);
                  leftButton->setFont(font);
                   rightButton->setFont(font);


         upButton->setText("↑");
        downButton->setText("↓");
         leftButton->setText("←");
         rightButton->setText("→");

         connect(upButton,&QPushButton::clicked,[=](){
             if(snakeDireaction!=moveMent::DOWN)
             snakeDireaction=moveMent::UP;
         });

         connect(downButton,&QPushButton::clicked,[=](){
             if(snakeDireaction!=moveMent::UP)
             snakeDireaction=moveMent::DOWN;
         });

         connect(leftButton,&QPushButton::clicked,[=](){
             if(snakeDireaction!=moveMent::RIGHT)
             snakeDireaction=moveMent::LEFT;
         });

         connect(rightButton,&QPushButton::clicked,[=](){
             if(snakeDireaction!=moveMent::LEFT)
             snakeDireaction=moveMent::RIGHT;
         });

    }

    //退出按钮
    {
        QPushButton * exitButton =new QPushButton(this);
        exitButton->setText("退出");
        QFont font("黑体",20);
        exitButton->setFont(font);
        exitButton->move(850,750);

        //消息盒子
        QMessageBox* message=new QMessageBox(this);
     QAbstractButton *ok=message->addButton("ok", QMessageBox::YesRole);
       QAbstractButton *cancel= message->addButton("cancel",QMessageBox::RejectRole);
        message->setWindowTitle("是否退出游戏？");
        connect(exitButton,&QPushButton::clicked,[=](){
            message->exec();
            QSound sound(":/clicked.wav");
            sound.play();
            //点击ok与cancel有不同的功能
            if(message->clickedButton()==ok)
            {
                this->close();
                QSound sound(":/clicked.wav");
                sound.play();
            }
            if(message->clickedButton()==cancel)
             {
                message->close();
                QSound sound(":/clicked.wav");
                sound.play();
            }
        });

    }
    //往文件里面写入分数
  int c=snakeList.size();
    QFile file(":/score.txt");
    if(file.open(QIODevice::WriteOnly|QIODevice::Text))
    {
           int data=c;
          QTextStream out(&file);
          out<<data;
           file.close();
    }




}


void gameroom::paintEvent(QPaintEvent *event)
{
    //画背景图
    QPainter painter(this);
    QPixmap pixmap;
    pixmap.load(":/cao.jPG");
    painter.drawPixmap(0,0,this->width()*0.8,this->height(),pixmap);
    pixmap.load(":/moon.jpg");
    painter.drawPixmap(this->width()*0.8,0,this->width()*0.2,this->height(),pixmap);



    //绘制蛇，蛇头，蛇身，蛇尾
    //绘制四个不同方向的蛇头
   {
        auto snakeHead=snakeList.front();
    if(snakeDireaction==moveMent::UP)
    {
        pixmap.load(":/up.png");
    }
    else if(snakeDireaction==moveMent::DOWN)
    {
         pixmap.load(":/down.png");
    }
    else if(snakeDireaction==moveMent::LEFT)
    {
          pixmap.load(":/left.png");
    }
    else
    {
        pixmap.load(":/right.png");
    }
   painter.drawPixmap(snakeHead.x(),snakeHead.y(),snakeWidth,snakeHeight,pixmap);
                }




   //绘制蛇身
  {
        for(int i =1;i<snakeList.size()-1;i++)
      {
       //获取蛇的一个结点
          auto snakeNode=snakeList.at(i);
           pixmap.load(":/body.png");
          painter.drawPixmap(snakeNode.x(),snakeNode.y(),snakeWidth,snakeHeight,pixmap);
       }
   //绘制蛇尾巴
      auto snakeTail=snakeList.back();
     painter.drawPixmap(snakeTail.x(),snakeTail.y(),snakeWidth,snakeHeight,pixmap);

    //绘制食物
     pixmap.load(":/food.jpg");
     painter.drawPixmap(foodNode.x(),foodNode.y(),snakeWidth,snakeHeight,pixmap);
    }
    //画分数图
    pixmap.load(":/score.png");
    painter.drawPixmap(this->width()*0.835,this->height()*0.06,150,80,pixmap);
    //显示分数
    QPen pen;
    pen.setColor("QColor(black)");
    painter.setPen(pen);
    QFont font("黑体",36);
    painter.setFont(font);
    painter.drawText(this->width()*0.90,this->height()*0.13,QString::number(snakeList.size()));

    //绘制游戏失败的效果
{
        if(checkFail())
        {
            QPen pen;
            pen.setColor(QColor("red"));
            painter.setPen(pen);
            QFont font("黑体",48);
            painter.setFont(font);
            painter.drawText(this->width()*0.3,this->height()*0.5,QString("GAME FAIL"));
              timer->stop();
            //QSound::play(":/gameover.png");
            //sound->stop();

        }

    }


}



//移动
void gameroom::moveUp()
{
    //左上角及右下角坐标
    QPointF leftTop;
    QPointF rightButtom;
    //获取头节点坐标,
    auto  head= snakeList.front();
    auto headX=head.x();
    auto headY=head.y();
    //
    if(headY<0)
    {
        leftTop=QPointF(headX,this->height()-snakeHeight);
    }
    else
    {
         leftTop=QPointF(headX,headY-snakeHeight);
    }
    rightButtom=leftTop+QPointF(snakeWidth,snakeHeight);

  snakeList.push_front(QRectF(leftTop,rightButtom));

}

void gameroom::moveDown()
{

    QPointF leftTop;
    QPointF rightButtom;
    //获取头节点坐标,
    auto  head= snakeList.front();
    auto headX=head.x();
    auto headY=head.y();
    //
    if(headY>this->height())
    {
        leftTop=QPointF(headX,snakeHeight);
    }
    else
    {
         leftTop=QPointF(headX,headY+snakeHeight);
    }
    rightButtom=leftTop+QPointF(snakeWidth,snakeHeight);

  snakeList.push_front(QRectF(leftTop,rightButtom));
}

void gameroom::moveLeft()
{
    QPointF leftTop;
    QPointF rightButtom;
    //获取头节点坐标,
    auto  head= snakeList.front();
    auto headX=head.x();
    auto headY=head.y();
    //
    if(headX<0)
    {
        leftTop=QPointF(this->width()-snakeWidth,headY);
    }
    else
    {
         leftTop=QPointF(headX-snakeWidth,headY);
    }
    rightButtom=leftTop+QPointF(snakeWidth,snakeHeight);

  snakeList.push_front(QRectF(leftTop,rightButtom));
}

void gameroom::moveRight()
{
    QPointF leftTop;
    QPointF rightButtom;
    //获取头节点坐标,
    auto  head= snakeList.front();
    auto headX=head.x();
    auto headY=head.y();
    //
    if(headX>this->width())
    {
        leftTop=QPointF(snakeWidth,headY);
    }
    else
    {
         leftTop=QPointF(headX+snakeWidth,headY);
    }
    rightButtom=leftTop+QPointF(snakeWidth,snakeHeight);

    snakeList.push_front(QRectF(leftTop,rightButtom));
}

//检查蛇是否撞到自己
bool gameroom::checkFail()
{
    for(int i=0;i<snakeList.size();i++)
    {
        for(int j=i+1;j<snakeList.size();j++)
        {
            if(snakeList.at(i)==snakeList.at(j))
            {
                return true;
            }
        }
    }
    return false;
}


//创造食物
void gameroom::creatFood()
{
    //这个坐标没怎么明白
    foodNode=QRectF(qrand()%800,qrand()%800,snakeWidth,snakeHeight);
}
